module UsersHelper
  def fields_for_username(username, &block)
    prefix = username.new_record? ? "new" : "existing"
    fields_for("user[#{prefix}_username_attributes][]", username, &block)
  end

#  :header_message => "Please try again!", :message => "The following problems were found while trying to save this user."
  def user_error_messages
    unless @user.errors.empty?
      header_message = content_tag "h2", "Please try again!"
      message = content_tag "p", "The following problems were found while trying to save this user."

      error_items = ""

      fname_error = errs_for(@user, 'fname')
      error_items << content_tag("li", "First Name " + fname_error) unless fname_error.blank?

      lname_error = errs_for(@user, 'lname')
      error_items << content_tag("li", "Last Name " + lname_error) unless lname_error.blank?

      email_error = errs_for(@user, 'email')
      error_items << content_tag("li", "Email " + email_error) unless email_error.blank?

      @user.usernames.each do |username|
        username.errors.each { |attr, msg|
          name = attr.gsub(/authentication_type_id/, "Authentication Service")
          error_items << content_tag("li", "#{name.titleize} #{msg}")
        }
      end
      
      unless error_items.blank?
        error_list = content_tag("ul", error_items)
      end

      content_tag "div", header_message + message + (error_list || ""), :id => "errorExplanation"
    end
  end

  private
  def errs_for(obj, attr)
    err = obj.errors.on(attr)
    err = err[0] if err.instance_of?(Array)
    return err
  end
end
